<?php

namespace App\Http\Resources;

use App\Models\CommentDetail;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Str;

class CommentDetailResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $routeName = \Route::currentRouteName();
        $onlyExcerpt = false;
        if (in_array($routeName, ['api.topic.index', 'api.topic.store']) || request('detail_excerpt')) {
            $onlyExcerpt = true;
        }
        return [
            'id' => $this->id,
            'cid' => $this->cid,
            'content' => $this->normalizeContent($this->content, $onlyExcerpt),
            'attachments' => AttachmentResource::collection($this->whenLoaded('attachments')),
        ];
    }

    public function normalizeContent($content, $onlyTextExcerpt = false)
    {
        $pureText = '';
        $imageOptions = [
            'crop' => 'limit',
            'quality' => 'auto',
        ];
        foreach ($content as &$item) {
            if ($item['type'] == CommentDetail::CONTENT_TYPE_IMAGE) {
                $imageOptions['format'] = $item['data']['format'] ?? null;
                $item['data']['url'] = attachmentUrl($item['data']['key'], 600, null, $imageOptions);
            } elseif ($item['type'] == CommentDetail::CONTENT_TYPE_TEXT) {
                $pureText .= $item['data']['text'];
            }
        }
        if ($onlyTextExcerpt) {
            return Str::limit($pureText, 125);
        } else {
            return $content;
        }
    }
}
